package com.atguigu.spzx.manager.handler;

import com.atguigu.spzx.model.dto.chat.ChatMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketHandler extends TextWebSocketHandler {

    // 用于存储用户ID和对应的WebSocketSession
    private static final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从WebSocket连接中获取用户ID
        String userSId = extractUserIdFromSession(session);
        if (userSId != null) {
            userSessions.put(userSId, session);
            System.out.println("New connection established for user: " + userSId + "  " + session);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 解析消息
        ChatMessage chatMessage = parseMessage(message.getPayload());
        if (chatMessage == null) {
            System.err.println("Invalid message format");
            return;
        }
        //调试作用
        System.out.println("Parsed message: " + chatMessage);

        // 获取目标用户的 userRId 和消息内容
        Long toUserId = chatMessage.getUserRId();
        String content = chatMessage.getContent();

        // 获取目标用户的 WebSocketSession
        WebSocketSession targetSession = userSessions.get(toUserId.toString()); // 注意：键是字符串类型
        if (targetSession != null && targetSession.isOpen()) {
            // 创建一个新的 ChatMessage 对象用于发送
            ChatMessage responseMessage = new ChatMessage();
            responseMessage.setUserRId(toUserId); // 设置接收者 ID
            responseMessage.setContent(content); // 设置消息内容

            // 将 ChatMessage 对象转换为 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResponse = objectMapper.writeValueAsString(responseMessage);

            System.out.println("Sending message to user: " + toUserId);
            targetSession.sendMessage(new TextMessage(jsonResponse)); // 发送 JSON 格式的消息
        } else {
            System.out.println("User " + toUserId + " is not connected.");
        }
        //调试作用
        System.out.println("User sessions: " + userSessions);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 从Map中移除关闭的会话
        String userId = extractUserIdFromSession(session);
        if (userId != null) {
            userSessions.remove(userId);
            System.out.println("Connection closed for user: " + userId);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 处理传输错误
        System.err.println("Transport error on session " + session.getId() + ": " + exception.getMessage());
    }

    private String extractUserIdFromSession(WebSocketSession session) {
        // 从WebSocketSession中提取用户ID
        // 这里假设用户ID是通过URL参数传递的，例如 ws://localhost:8501/websocket/123
        String path = session.getUri().getPath();
        return path.substring(path.lastIndexOf('/') + 1);
    }

    private ChatMessage parseMessage(String payload) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将 JSON 字符串解析为 ChatMessage 对象
            return objectMapper.readValue(payload, ChatMessage.class);

        } catch (Exception e) {
            System.err.println("Failed to parse message: " + e.getMessage());
            return null;
        }

    }
}